
const apiUrl = 'http://yuesao.eduwr.com/miniapp'
// 个人信息端口
// const apiUrl = 'http://192.168.2.5:8080/miniapp'
// const apiUrl = 'http://192.168.2.6:8080/miniapp'

let app = getApp();

function http(opt) {
	var _this = this
	let token = uni.getStorageSync('token')||''
	// 获取请求参数
	opt = opt || {}
	opt.url = opt.url || ''
	opt.data = opt.data || {}
	opt.method = opt.method || 'POST'
	opt.headerState = opt.headerState || 0
	opt.headerobj = opt.headerobj || {}

	let contentType = 'application/json;charset=UTF-8'

	// 设置请求头
	switch (opt.headerState) {
		
		case 0:
			contentType = 'application/json;charset=UTF-8'
			break
		case 1:
			contentType = 'application/x-www-form-urlencoded'
			break
		case 2:
			contentType = 'multipart/form-data'
			break
	}
	opt.header = {
		'Content-Type': contentType,
		Authorization: token,
	}
	// 使用Promise异步请求接口
	return new Promise((resolve, reject) => {
		var url = opt.url
		if (url.indexOf('https') < 0) {
			url = apiUrl + opt.url
		}
		uni.showLoading({
			title: '加载中'
		});
		uni.request({
			url: url,
			data: opt.data,
			method: opt.method,
			header: opt.header,
			dataType: 'json',
			success: function(res) {
				if (res.data.code == 200 || res.statusCode == 200 || res.success == true || res.data
					.success == true) {
					// 请求接口成功且后台返回正确信息
					resolve(res.data)
				}
				if (res.data.code == 401) {
					// 请求接口成功但后台返回错误信息
					uni.showToast({
						title: res.data.msg,
						icon: 'none',
						duration: 1500

					})
					// _this.$toast(res.data.msg)
					setTimeout(() => {
						uni.clearStorageSync()
						uni.redirectTo({
								url: '/pages/login/login'
						})
					}, 1500)
					reject(res.data)
				}
				if (res.data.code == '-100' || res.data.code == -100 ) {
					console.log('----')
					uni.showToast({
						title: res.data.msg,
						icon: 'none',
						duration: 1500
					})
					reject(res.data)
				}
				if (res.data.code == '-100' && !res.data.success) {
					reject(res.data)
				}
				if (res.data.code == 500) {

					uni.showToast({
						title: res.data.msg,
						icon: 'none',
						duration: 1500

					})
					reject(res)
				}
				if (res.data.success == false) {
					reject(res)
				}
			},
			fail: function(res) {
				// 请求接口失败
				reject(res)
			},
			complete: function(res) {
				uni.hideLoading()
				if (res.statusCode === 500||res.statusCode === 404) {
					uni.showToast({
						title: '服务器维护中',
						icon: 'none'
					})
					reject(res)
				}
				if (res.statusCode === 502) {
					uni.showToast({
						title: '服务器更新，请稍后重试',
						icon: 'none'
					})
					reject(res)
				}
				if (res.statusCode === 400) {
					uni.showToast({
						title: 'statusCode 400',
						icon: 'none',
						duration: 1500
					})
					reject(res)
				}
			},
		})
	})
}

export default {
	http,
}
